import {
  Controller,
  Headers,
  Post,
  UploadedFile,
  UseInterceptors,
  Res,
  Get,
} from '@nestjs/common';
import { UploadService } from './upload.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { Response } from 'express';
import { join } from 'path';
import { zip } from 'compressing';

@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Post('images')
  @UseInterceptors(FileInterceptor('file'))
  upload(@UploadedFile() file, @Headers('cookie') headers) {
    console.log(file);
    console.log(headers);
    return {
      code: 200,
    };
  }

  // 直接返回图片
  @Get('export')
  export(@Res() res: Response) {
    const url = join(__dirname, '../images/1711875007408.png');
    res.download(url);
  }

  @Get('stream') // 返回流的方式
  async stream(@Res() res: Response) {
    const url = join(__dirname, '../images/1711875007408.png');
    // 创建zip压缩流
    const tarStream = new zip.Stream();
    // 将图片文件写入压缩流中
    await tarStream.addEntry(url);
    // 设置响应头: 表示以流的方式返回
    res.setHeader('Content-Type', 'application/octet-stream');
    res.setHeader('Content-Disposition', `attachment; filename=earth`);
    tarStream.pipe(res); // 返回前端
  }
}
